package com.cuizhang.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.List;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.ll.core.action.QueryAction;
import com.ll.core.magzine.model.bean.Period;
import com.ll.core.util.CommonTool;
import com.ll.core.util.JSONTool;
import com.ll.core.util.TypeTokens;
import com.ll.core.view.util.ViewUtil;

public class LastPeriodActivity extends MyBaseListActivity {

	private List<Period> periods;
	private SimpleAdapter adapter;
	private ListView lv;
	private ArrayAdapter<Period> arrayAdapter = null;
	private String year;
	private final static int DIALOG_LOADING = 1001;
	private ProgressDialog dialog;

//	private String[] dates = new String[] { "2012年02月20日", "2012年02月15日",
//			"2012年02月10日", "2012年02月05日", "2012年02月01日", "2012年01月25日",
//			"2012年01月20日", "2012年01月15日", "2012年01月10日", "2012年01月08日",
//			"2012年01月5日", "2012年01月01日" };;
//	private String[] stageByYears = new String[] { "12", "11", "10", "9", "8",
//			"7", "6", "5", "4", "3", "2", "1" };
//	private String[] stageByAlls = new String[] { "270", "269", "268", "267",
//			"266", "265", "264", "263", "262", "261", "260", "259" };
//	private final int[] imageIds = new int[] { R.drawable.p1, R.drawable.p2,
//			R.drawable.p3, R.drawable.p4, R.drawable.p5, R.drawable.p6,
//			R.drawable.p7, R.drawable.p8, R.drawable.p9, R.drawable.p10,
//			R.drawable.p11, R.drawable.p12 };

	private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	private static String[] years = new String[] { "2009", "2010", "2011" };
	private int current = years.length - 1;
	public static class ViewHolder {
		public TextView dateTv;// 发布时间
		public TextView periodTv;// 发布期别
		public ImageView coverIv;// 封面
		// public TextView lastPublisher;
	}

	private class PeriodArrayAdapter<T> extends ArrayAdapter {
		private int ResourceId;
		private LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		public PeriodArrayAdapter(Context context, int textViewResourceId,
				List objects) {
			super(context, textViewResourceId, objects);
			this.ResourceId = textViewResourceId;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Log.i("test", "getView " + position + " " + convertView);
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(ResourceId, null);
				holder = new ViewHolder();
				holder.dateTv = (TextView) convertView.findViewById(R.id.date);
				holder.periodTv = (TextView) convertView
						.findViewById(R.id.period);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			Period period = (Period) this.getItem(position);
			holder.dateTv.setText(CommonTool.DateToString(period.getPublish_time(),"yyyy年MM月dd日"));// 发布时间
			holder.periodTv.setText("总第"+period.getPeriod()+"期");// 发布年度
			return convertView;
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.period_main);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.title_text);

		final TextView tv = (TextView) findViewById(R.id.title);
		tv.setText(years[years.length - 1] + "年");
		this.year = years[years.length - 1];
		// generateData();

		lv = getListView();

		Button btn = (Button) findViewById(R.id.back);
		btn.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				finish();
			}
		});

		ImageView btnLeft = (ImageView) findViewById(R.id.search_stock_left);
		btnLeft.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if (current > 0) {
					current--;
					LastPeriodActivity.this.year = String.valueOf(years[current]);
					loadData();
					tv.setText(years[current] + "年");
				}

			}
		});

		ImageView btnRight = (ImageView) findViewById(R.id.search_stock_right);
		btnRight.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if (current < years.length - 1) {
					current++;
					LastPeriodActivity.this.year = String.valueOf(years[current]);
					loadData();
					tv.setText(years[current] + "年");
					
				}
			}
		});

		loadData();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		Intent i = new Intent(LastPeriodActivity.this, StageActivity.class);
		
		i.putExtra("period", JSONTool.ObjectToJSON(this.arrayAdapter.getItem(position)));
		//i.put("period", this.periods.get((int)id));
//		i.putExtra("dates", dates);
//		i.putExtra("stageByYears", stageByYears);
//		i.putExtra("stageByAlls", stageByAlls);
//		i.putExtra("imageIds", imageIds);
//		i.putExtra("index", 5);

		startActivity(i);
	}

	private synchronized void loadData() {
		 new ProgressTask().execute();
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_LOADING:
			dialog = new ProgressDialog(this);
			dialog.setMessage("数据加载中......");
			dialog.setIndeterminate(true);
			// dialog.setCancelable(true);
			return dialog;

		}
		return super.onCreateDialog(id);
	}

	private class ProgressTask extends AsyncTask<Void, Void, Void> {

		
		int[] ids = new int[] { R.raw.f1, R.raw.f2, R.raw.f3, R.raw.f4,
				R.raw.f5, R.raw.f6, R.raw.f7, R.raw.f8, R.raw.f9, R.raw.f10 };

		@Override
		protected void onPreExecute() {
			showDialog(DIALOG_LOADING);
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			List<Period> periods = null;
			try {
				Log.i("INFO", year);
				periods = QueryAction.getInstance().queryPeriodsByYear(year);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return;
			}
			if(periods == null){
				return;
			}
			if(periods.size() == 0){
				Log.i("INFO", "没有返回数据!");
			}
			System.out.println(periods.size());
			if (LastPeriodActivity.this.arrayAdapter == null) {
				LastPeriodActivity.this.arrayAdapter = new PeriodArrayAdapter<Period>(
						LastPeriodActivity.this, R.layout.period_row, periods);
				lv.setAdapter(arrayAdapter);
				
			} else {
				System.out.println(LastPeriodActivity.this.arrayAdapter);
				LastPeriodActivity.this.arrayAdapter.clear();
				for (Period p : periods) {
					LastPeriodActivity.this.arrayAdapter.add(p);
				}
				LastPeriodActivity.this.lv.setSelection(0);
			}

			removeDialog(DIALOG_LOADING);
			super.onPostExecute(result);
		}
	}

	// private class MySimpleAdapter extends SimpleAdapter {
	//
	// private String[] mFrom;
	// private List<? extends Map<String, ?>> mData;
	// private int[] mTo;
	//
	// public MySimpleAdapter(Context context, List<? extends Map<String, ?>>
	// data, int resource, String[] from, int[] to) {
	// super(context, data, resource, from, to);
	// mFrom = from;
	// mData = data;
	// mTo = to;
	// }
	//
	// public View getView(int position, View convertView, ViewGroup parent) {
	// View lineView = super.getView(position, convertView, parent);
	// // final int pos = position;
	// // final Article vo = vos.get(position);
	// //
	// // // // logo
	// // // ImageView logo = (ImageView)
	// // ImageView v = (ImageView) lineView.findViewById(R.id.app_icon);
	// // if (position % 4 == 0) {
	// // v.setImageDrawable(getResources().getDrawable(R.drawable.t1));
	// // } else if (position % 4 == 1) {
	// // v.setImageDrawable(getResources().getDrawable(R.drawable.t2));
	// // } else if (position % 4 == 2) {
	// // v.setImageDrawable(getResources().getDrawable(R.drawable.t3));
	// // } else {
	// // v.setImageDrawable(getResources().getDrawable(R.drawable.t4));
	// // }
	// //
	// // TextView tv = (TextView) lineView.findViewById(R.id.content);
	// // String str = vos.get(position).getSimpleDesc();
	// // tv.setText(Html.fromHtml(str));
	//
	// return lineView;
	//
	// }
	// }

	/**
	 * 读取配置文件
	 * 
	 * @return
	 */
	private String getFromRaw(int fileName) {
		BufferedReader br = null;
		InputStream is = null;
		StringBuffer sb = null;
		try {
			is = getResources().openRawResource(fileName);
			br = new BufferedReader(new InputStreamReader(is));
			sb = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
		return sb.toString();
	}

}
